<template>
  <div class="container">
    <el-dialog
      title="新增标签"
      :visible="showAdd"
      width="30%"
      @close="closeDialog"
    >
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item v-if="!$route.query.subjectID" label="所属学科" prop="select">
          <el-select v-model="form.subjectID" placeholder="请选择" >
            <el-option v-for="item in options"
              :key="item.id"
              :label="item.subjectName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName" >
          <el-input v-model="form.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list } from '@/api/hmmm/subjects.js'
import { add, update } from '@/api/hmmm/tags.js'
export default {
  watch: {
    tagById () {
      this.form.tagName = this.tagById.tagName
      this.form.subjectID = this.tagById.subjectID
    }
  },
  props: {
    tagById: {
      type: Object,
      default: () => { }
    },
    showAdd: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      options: {}, // 学科列表123
      form: {
        subjectID: null,
        tagName: ''
      },
      rules: {
        tagName: [
          { required: true, message: '请输入标签名称', trigger: 'blur' }
        ],
        select: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.getSubjectList()
  },
  methods: {
    // 获取学科
    async getSubjectList () {
      const { data } = await list()
      // console.log(data)
      this.options = data.items
    },
    // 关闭弹层
    closeDialog () {
      this.$emit('close_dialog')
      this.form = {
        subjectID: null,
        tagName: ''
      }
      this.$refs.form.resetFields()
    },
    onSubmit () {
      // 表单校验
      this.$refs.form.validate(async isOk => {
        if (isOk) {
          try {
            if (this.tagById.id) {
              await update({ ...this.form, id: this.tagById.id })
            } else {
              await add(this.form)
            }
            this.$emit('change_dialog')
            this.$message.success(`${this.tagById.id ? '修改' : '新增'}成功`)
            this.closeDialog()
          } catch (error) {
            this.$message.error(error)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input__inner {
    width: 250px;
}
</style>
